<html>
<script>
var deliciousUrl = "http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url=";

function add_delicious(url, title, notes)
{
  var request = deliciousUrl + encodeURIComponent(url) + '&title=' + encodeURIComponent(title);
  
  if (notes)
    request += '&notes=' + encodeURIComponent(notes);
    
  console.debug('send request: ' + request);
  
  window.open(request, 'deliciousuiv5','location=yes,links=no,scrollbars=no,toolbar=no,width=550,height=550');
}

var ports = {};

chrome.extension.onConnect.addListener(function(port) {
  ports[port.tab.id] = port;
  
  console.debug("bind tab #" + port.tab.id + " w/ " + port.tab.url);
  
  port.onMessage.addListener(function(msg) {
    console.debug("receive command: " + msg.cmd + ", url: " + msg.url + ", title: " + msg.title + ", selection: " + msg.selection);
    
    if (msg.cmd == 'getSelection')
    {
      add_delicious(msg.url, msg.title, msg.selection);
    }
  });
});

chrome.pageActions["TagPageAction"].addListener(function(pageActionId, info) {   
   chrome.windows.getCurrent(function(win) {
        console.debug("action occured in window #" + win.id);
        
        chrome.tabs.get(info.tabId, function(tab) {
            if (win.focused) {
               var port = ports[info.tabId];
                      
               if (port)
               {
                 port.postMessage({cmd: 'getSelection', url: tab.url, title: tab.title});
               }
               else
               {
                 // TODO: get the missing port with chrome.tabs
                 add_delicious(tab.url, tab.title, '');
               }
            }
        });
    });
});
</script>
</html>
